#include "thread_pool.h"

int simpleTransferFile(int sockfd, const char *filename) {
    printf("Filename: %s\n", filename);

    // 动态分配 train_t 结构体内存
    train_t *t = (train_t *)malloc(sizeof(train_t) + strlen(filename) + 1);
    if (t == NULL) {
        perror("malloc");
        return -1;
    }

    // 发送文件名长度 (包括字符串结束符)
    t->len = strlen(filename) + 1; // +1 for null terminator
    send(sockfd, &(t->len), sizeof(t->len), 0);

    // 发送文件名 (包括字符串结束符)
    strcpy(t->buff, filename);
    send(sockfd, t->buff, t->len, 0);

    int fd = open(filename, O_RDONLY);
    if (fd == -1) {
        perror("open");
        free(t);
        return -1;
    }

    // 获取文件信息
    struct stat fileInfo;
    if (fstat(fd, &fileInfo) == -1) {
        perror("fstat");
        close(fd);
        free(t);
        return -1;
    }

    // 发送文件大小
    off_t file_size = fileInfo.st_size;
    printf("File size: %ld bytes\n", file_size);
    send(sockfd, &file_size, sizeof(file_size), 0);

    // **** 断点续传 ****
    // 接收已接收文件大小
    off_t received_size;
    recv(sockfd, &received_size, sizeof(received_size), 0);
    printf("Client has received: %ld bytes\n", received_size);

    // 定位文件指针到已接收数据之后
    off_t remaining_size = file_size - received_size;
    if (lseek(fd, received_size, SEEK_SET) == -1) {
        perror("lseek failed");
        close(fd);
        free(t);
        return -1;
    }

    // 发送未发送的部分文件内容
    if (remaining_size > 0) {
        printf("Sending remaining %ld bytes...\n", remaining_size);
        ssize_t nwrite;
        char buffer[4096];
        while (remaining_size > 0) {
            ssize_t read_bytes = read(fd, buffer, sizeof(buffer));
            if (read_bytes < 0) {
                perror("read failed");
                close(fd);
                free(t);
                return -1;
            }

            if (read_bytes == 0)
                break;

            nwrite = send(sockfd, buffer, read_bytes, 0);
            if (nwrite <= 0) {
                perror("send failed");
                close(fd);
                free(t);
                return -1;
            }
            remaining_size -= nwrite;
        }
    }

    close(fd);
    free(t);
    printf("File successfully sent.\n");
    return 0;
}
